# -*- coding: utf-8 -*-
from django import template
from warehouse.models import PurchaseRequestStatusList,PurchaseRequest,PurchaseRequestItems,PR_STATUS_CHOICES
from warehouse.models import PurchaseOrder,PurchaseOrderDetail,PO_STATUS_CHOICES
from warehouse.models import PurchaseReceipt,PurchaseReceiptDetail,Receipt_STATUS_CHOICES
from warehouse.models import StockOut,StockOutItem,StockOut_STATUS_CHOICES
from warehouse.models import Employee
import re
import math
from django.db.models import Q
import logging,datetime
import string
from django.utils.encoding import force_unicode
from django.conf import settings

register = template.Library()

base_url = '/erp'

numeric_test = re.compile("^\d+$")

@register.filter
def getattribute(value, arg):
    """Gets an attribute of an object dynamically from a string name"""
    
    if hasattr(value, str(arg)):
        return getattr(value, arg)
    elif hasattr(value, 'has_key') and value.has_key(arg):
        return value[arg]
    elif numeric_test.match(str(arg)) and len(value) > int(arg):
        return value[int(arg)]
    else:
        return settings.TEMPLATE_STRING_IF_INVALID

@register.simple_tag(takes_context=True)
def getsubmit(context, key):
    request = context['request']
    value = None
    if request.method == 'POST':        
        value = request.POST.get(key,None)        
        #logging.error('post')
    else:         
        value = request.GET.get(key,None)
    
    return value
                                        
@register.filter
def in_group(user, groups):
    """Returns a boolean if the user is in the given group, or comma-separated
    list of groups.

    Usage::

        {% if user|in_group:"Friends" %}
        ...
        {% endif %}

    or::

        {% if user|in_group:"Friends,Enemies" %}
        ...
        {% endif %}

    """
    group_list = force_unicode(groups).split(',')
    return bool(user.groups.filter(name__in=group_list).values('name'))

@register.filter
def get_base_url(str):
    return "/erp"
    
@register.simple_tag
def show_mydate_display(mydate):
    mydateobj =None
    if  isinstance(mydate,datetime.datetime) or isinstance(mydate,datetime.date) :
        mydateobj = datetime.datetime(mydate.year,mydate.month,mydate.day)
    else:
        mydateobj = datetime.datetime(mydate['year'],mydate['month'],mydate['day']) 
        
    if mydateobj.date()==datetime.datetime.now().date():
        return u"今日"
    elif mydateobj.date()==(datetime.datetime.now() - datetime.timedelta(days=1)).date():
        return u"昨日"
    else:
        if int(mydateobj.year)==datetime.datetime.now().date().year:
            return u"%s月%s日"%(mydateobj.month,mydateobj.day)
        else:
            return u"%s年%s月%s日"%(mydateobj.year,mydateobj.month,mydateobj.day)


@register.inclusion_tag('inc_func/pr/list.html', takes_context=True)
def show_pr_list(context,pagesize=2,show_pr_pager=0):    
    request = context['request']
    pr_choice = list(PR_STATUS_CHOICES)
    pr_choice = [x for x,_ in pr_choice]
    begintime = None
    endtime = None
    keywords = None
    page=1
    if request.method == 'POST':
        pr_choice = request.POST.getlist('STATUS_CHOICES')
        begintime = request.POST.get('begintime','')
        endtime = request.POST.get('endtime','')
        keywords = request.POST.get('keywords','')            
        #logging.error('post')
    else:
        pr_choice = list( request.GET.get('status',string.join(pr_choice,''))) 
        page = request.GET.get('p','')
        begintime = request.GET.get('begintime','')
        endtime = request.GET.get('endtime','')
        keywords = request.GET.get('keywords','')
        if page:
            page= int(page)
        else:
            page=1
    
    #一般员工，列出自己提出的申请；列出自己为审批人的；采购列出全部
    pr_items = PurchaseRequest.objects.filter(PR_Ststus__in=pr_choice)
    pr_items = pr_items.filter(PR_Use__contains=keywords)
    
    
    if begintime:
        pr_items = pr_items .filter( PR_DateTime__gte = datetime.datetime.strptime(begintime,'%Y-%m-%d') )
    if endtime:
        pr_items = pr_items .filter( PR_DateTime__lte = datetime.datetime.strptime(endtime,'%Y-%m-%d') )
    
    #logging.error(begintime)
    
    #采购列出全部
    #logging.error(in_group(request.user,u'采购'))
    #request.user.groups.all():     
    if request.user.id and in_group(request.user,u'采购') :
        #pr_items = PurchaseRequest.objects.all(PR_Ststus__in=pr_choice).order_by('-PR_LastModify_Date')
        pr_items = pr_items.order_by('-PR_LastModify_Date')
        #logging.error('ok')
    else:
        #logging.error( in_group(request.user,u'采购'))
        #emp = Employee.GetEmployeeFromUser(request.user)
        username = request.user.id
        #pr_items = PurchaseRequest.objects.filter( Q(PR_Apply_User__Emp_User__id__exact=username)|(~Q(PR_Ststus='I') & Q(PR_Adult_User__Emp_User__id__exact=username))).order_by('-PR_LastModify_Date')
        pr_items = pr_items.filter( Q(PR_Apply_User__Emp_User__id__exact=username)|(~Q(PR_Ststus='I') & Q(PR_Adult_User__Emp_User__id__exact=username))).order_by('-PR_LastModify_Date')
        
    record_count = pr_items.count()
    page_count = str(int(math.ceil(float(record_count)/float(pagesize))))
    first_this_page = (int(page)-1)*pagesize
    last_this_page = min(record_count,int(page)*pagesize)
    
    queryparam = {
                          'query':'?begintime='+begintime+'&endtime='+endtime+'&status='+string.join(pr_choice,'')+'&',
                          'qpage':page,                           
                          'record_count':record_count,
                          'pagesize':pagesize,
                          'pagecount':page_count,
                          'first_this_page':first_this_page+1,
                          'last_this_page':last_this_page,
                          #'cache_key':cache_key,
                          #'cache_key_no_page':cache_key_no_page,
                          }  
    info = pr_items[first_this_page :last_this_page]
    return {'items':info,
            'queryparam':queryparam,
            'show_pager':show_pr_pager,
            'STATUS_CHOICES':PR_STATUS_CHOICES,
            'STATUS_CHOICES_POST':pr_choice,
            'current_url':base_url+'/pr/',
            'workflow_png':'pr.png',
            'current_date':datetime.datetime.now(),
            'begintime':begintime,
            'endtime':endtime,
            'keywords':keywords,
            }

@register.inclusion_tag('inc_func/pr/items_list.html', takes_context=True)
def show_pr_items_list(context,pr_id):   
    pr_items = PurchaseRequestItems.objects.filter(PRI_PurchaseRequest__id=pr_id).order_by('id')
    p_r = PurchaseRequest.objects.get(pk=pr_id)
    p_r.user =  context['request'].user
    return {'pr_items':pr_items,'pr_id':pr_id,'pr':p_r,'current_url':base_url+'/pr/'}

@register.inclusion_tag('inc_func/status.html', takes_context=True)
def show_pr_status(context,id):       
    request = context['request']
    p_r = PurchaseRequest.objects.get(pk=id)
    p_r.user = request.user
    
    return {'id':id,'obj':p_r, 
            'current_url':base_url+'/pr/','statuslist':PurchaseRequestStatusList}


from warehouse.models import PurchaseOrderStatusList

@register.inclusion_tag('inc_func/po/list.html', takes_context=True)
def show_po_list(context,pagesize=2,show_po_pager=0):    
    request = context['request']
    p_choice = list(PO_STATUS_CHOICES)
    p_choice = [x for x,_ in p_choice]
    begintime = None
    endtime = None
    keywords = None
    page=1
    if request.method == 'POST':
        p_choice = request.POST.getlist('STATUS_CHOICES')
        begintime = request.POST.get('begintime','')
        endtime = request.POST.get('endtime','')
        keywords = request.POST.get('keywords','')   
    else:
        p_choice = list( request.GET.get('status',string.join(p_choice,''))) 
        page = request.GET.get('p','')
        begintime = request.GET.get('begintime','')
        endtime = request.GET.get('endtime','')
        keywords = request.GET.get('keywords','')
        if page:
            page= int(page)
        else:
            page=1
    
    #一般员工，列出自己提出的申请；列出自己为审批人的；采购列出全部
    result_items = PurchaseOrder.objects.filter(PO_Ststus__in=p_choice)
    result_items = result_items.filter(PO_Title__contains=keywords)
    
    if begintime:
        result_items = result_items .filter( PO_DateTime__gte = datetime.datetime.strptime(begintime,'%Y-%m-%d') )
    if endtime:
        result_items = result_items .filter( PO_DateTime__lte = datetime.datetime.strptime(endtime,'%Y-%m-%d') )
    
    
    current_user = Employee.GetEmployeeFromUser(request.user)
    
    #采购列出全部
    #logging.error(p_choice)
    #logging.error(in_group(request.user,u'采购'))   
    if request.user.id and in_group(request.user,u'采购'):
        #logging.error('采购')
        pass
    elif request.user.id and in_group(request.user,u'仓库') and not in_group(request.user,u'财务') :
        result_items = result_items.filter( Q(PO_Ststus='Z')|(Q(PO_Employee_Audit =current_user)&(~Q(PO_Ststus='I') )))
    elif request.user.id and in_group(request.user,u'财务') and not in_group(request.user,u'仓库') :
        result_items = result_items.filter( Q(PO_Ststus__in=['Z','F'])|(Q(PO_Employee_Audit =current_user)&(~Q(PO_Ststus='I') )))    
    elif request.user.id and in_group(request.user,u'财务') and in_group(request.user,u'仓库') :
        result_items = result_items.filter( Q(PO_Ststus__in=['Z','F'])|(Q(PO_Employee_Audit =current_user)&(~Q(PO_Ststus='I') )))
    else:
        result_items = result_items.filter( Q(PO_Employee_Audit=current_user)&(~Q(PO_Ststus='I') ))
    
    result_items = result_items.order_by('-PO_LastModify_Date')    
    record_count = result_items.count()
    #logging.error(record_count)
    page_count = str(int(math.ceil(float(record_count)/float(pagesize))))
    first_this_page = (int(page)-1)*pagesize
    last_this_page = min(record_count,int(page)*pagesize)
    
    queryparam = {
                          'query':'?status='+string.join(p_choice,'')+'&',
                          'qpage':page, 
                          'record_count':record_count,
                          'pagesize':pagesize,
                          'pagecount':page_count,
                          'first_this_page':first_this_page+1,
                          'last_this_page':last_this_page,
                          #'cache_key':cache_key,
                          #'cache_key_no_page':cache_key_no_page,
                          }  
    info = result_items[first_this_page :last_this_page]
    return {'po_items':info,
            'queryparam':queryparam,
            'show_pager':show_po_pager,
            'STATUS_CHOICES':PO_STATUS_CHOICES,
            'STATUS_CHOICES_POST':p_choice,
            'workflow_png':'po.png',
            'user':request.user,
            'current_url':base_url+'/po/',
            'begintime':begintime,
            'endtime':endtime,
            'keywords':keywords,
            }

@register.inclusion_tag('inc_func/po/items_list.html', takes_context=True)
def show_po_items_list(context,po_id):   
    result_items = PurchaseOrderDetail.objects.filter(POD_PurchaseOrder__id=po_id).order_by('id')
    po = PurchaseOrder.objects.get(pk=po_id)
    po.user  =  context['request'].user
    return {'po_items':result_items,'po_id':po_id,'p_o_status':po,'current_url':base_url+'/po/'}

@register.inclusion_tag('inc_func/status.html', takes_context=True)
def show_po_status(context,po_id):       
    request = context['request']
    p = PurchaseOrder.objects.get(pk=po_id)
    p.user = request.user
    
    return {'id':po_id,'obj':p, 'statuslist':PurchaseOrderStatusList,
             'current_url':base_url+'/po/'}

from warehouse.models import PurchaseReceiptStatusList

@register.inclusion_tag('inc_func/receipt/list.html', takes_context=True)
def show_re_list(context,pagesize=2,show_pager=0):    
    request = context['request']
    choice = list(Receipt_STATUS_CHOICES)
    choice = [x for x,_ in choice]
    begintime = None
    endtime = None
    keywords = None
    page=1
    if request.method == 'POST':
        choice = request.POST.getlist('STATUS_CHOICES')
        begintime = request.POST.get('begintime','')
        endtime = request.POST.get('endtime','')
        keywords = request.POST.get('keywords','')   
    else:
        choice = list( request.GET.get('status',string.join(choice,''))) 
        page = request.GET.get('p','')
        begintime = request.GET.get('begintime','')
        endtime = request.GET.get('endtime','')
        keywords = request.GET.get('keywords','')
        if page:
            page= int(page)
        else:
            page=1
    
    #一般员工，列出自己提出的申请；列出自己为审批人的；采购列出全部
    result_items = PurchaseReceipt.objects.filter(PR_Ststus__in=choice)
    result_items = result_items.filter(PR_Title__contains=keywords)
    
    if begintime:
        result_items = result_items .filter( PR_CreateDateTime__gte = datetime.datetime.strptime(begintime,'%Y-%m-%d') )
    if endtime:
        result_items = result_items .filter( PR_CreateDateTime__lte = datetime.datetime.strptime(endtime,'%Y-%m-%d') )
    
    #采购列出全部
    #logging.error(p_choice)
    #logging.error(in_group(request.user,u'采购'))   
    if request.user.id and in_group(request.user,u'仓库'):
        #pr_items = PurchaseRequest.objects.all(PR_Ststus__in=pr_choice).order_by('-PR_LastModify_Date')
        result_items = result_items.order_by('-PR_LastModify_Date')
        #logging.error('采购')
    else:
        username = request.user.id
        result_items = result_items.filter( Q(PR_ReceiptEmployee__Emp_User__id__exact=username)&(~Q(PR_Ststus='I') )).order_by('-PR_LastModify_Date')
    
    
    record_count = result_items.count()
    #logging.error(record_count)
    page_count = str(int(math.ceil(float(record_count)/float(pagesize))))
    first_this_page = (int(page)-1)*pagesize
    last_this_page = min(record_count,int(page)*pagesize)
    
    queryparam = {
                          'query':'?status='+string.join(choice,'')+'&',
                          'qpage':page, 
                          'record_count':record_count,
                          'pagesize':pagesize,
                          'pagecount':page_count,
                          'first_this_page':first_this_page+1,
                          'last_this_page':last_this_page,
                          #'cache_key':cache_key,
                          #'cache_key_no_page':cache_key_no_page,
                          }  
    info = result_items[first_this_page :last_this_page]
    return {'items':info,
            'queryparam':queryparam,
            'show_pager':show_pager,
            'STATUS_CHOICES':Receipt_STATUS_CHOICES,
            'STATUS_CHOICES_POST':choice,
            'workflow_png':'re.png',
            'user':request.user,
            'current_url':base_url+'/re/',
            'begintime':begintime,
            'endtime':endtime,
            'keywords':keywords,
            }

@register.inclusion_tag('inc_func/receipt/items_list.html', takes_context=True)
def show_re_items_list(context,id):
    result_items = PurchaseReceiptDetail.objects.filter(PurchaseReceipt__id=id).order_by('id')
    re = PurchaseReceipt.objects.get(pk=id)
    re.user = context['request'].user
    return {'items':result_items,'id':id,'status':re,'current_url':base_url+'/re/',}

@register.inclusion_tag('inc_func/status.html', takes_context=True)
def show_re_status(context,id):
    request = context['request']
    p = PurchaseReceipt.objects.get(pk=id)
    p.user = request.user
    
    return {'title':'入库','id':id,'obj':p, 'statuslist':PurchaseReceiptStatusList,
            'current_url':base_url+'/re/',}


#StockOut,StockOutItem,StockOutStatus,StockOut_STATUS_CHOICES

from warehouse.models import StockOutStatusList

@register.inclusion_tag('inc_func/stockout/list.html', takes_context=True)
def show_so_list(context,pagesize=2,show_pager=0):    
    request = context['request']
    choice = list(StockOut_STATUS_CHOICES)
    choice = [x for x,_ in choice]
    begintime = None
    endtime = None
    keywords = None
    page=1
    if request.method == 'POST':
        choice = request.POST.getlist('STATUS_CHOICES')
        begintime = request.POST.get('begintime','')
        endtime = request.POST.get('endtime','')
        keywords = request.POST.get('keywords','')   
    else:
        choice = list( request.GET.get('status',string.join(choice,'')))
        begintime = request.GET.get('begintime','')
        endtime = request.GET.get('endtime','') 
        page = request.GET.get('p','')
        keywords = request.GET.get('keywords','')
        if page:
            page= int(page)
        else:
            page=1
    
    #一般员工，列出自己提出的申请；列出自己为审批人的；采购列出全部
    result_items = StockOut.objects.filter(Ststus__in=choice)
    result_items = result_items.filter(Title__contains=keywords)
    
    if begintime:
        result_items = result_items .filter( CreateDateTime__gte = datetime.datetime.strptime(begintime,'%Y-%m-%d') )
    if endtime:
        result_items = result_items .filter( CreateDateTime__lte = datetime.datetime.strptime(endtime,'%Y-%m-%d') )
    
    #采购列出全部
    #logging.error(p_choice)
    #logging.error(in_group(request.user,u'采购'))   
    if request.user.id and in_group(request.user,u'仓库'):
        #pr_items = PurchaseRequest.objects.all(PR_Ststus__in=pr_choice).order_by('-PR_LastModify_Date')
        #result_items = result_items.order_by('-LastModify_Date')
        #logging.error('采购')
        pass
    else:
        username = request.user.id
        result_items = result_items.filter( (Q(AuditMan__Emp_User__id__exact=username)&(~Q(Ststus='I') )) |  Q(ApplyMan__Emp_User__id__exact=username)  )  
    
    result_items = result_items.order_by('-LastModify_Date')
    
    record_count = result_items.count()
    #logging.error(record_count)
    page_count = str(int(math.ceil(float(record_count)/float(pagesize))))
    first_this_page = (int(page)-1)*pagesize
    last_this_page = min(record_count,int(page)*pagesize)
    
    queryparam = {
                          'query':'?status='+string.join(choice,'')+'&',
                          'qpage':page, 
                          'record_count':record_count,
                          'pagesize':pagesize,
                          'pagecount':page_count,
                          'first_this_page':first_this_page+1,
                          'last_this_page':last_this_page,
                          
                          #'cache_key':cache_key,
                          #'cache_key_no_page':cache_key_no_page,
                          }  
    info = result_items[first_this_page :last_this_page]
    return {'items':info,
            'queryparam':queryparam,
            'show_pager':show_pager,
            'STATUS_CHOICES':StockOut_STATUS_CHOICES,
            'STATUS_CHOICES_POST':choice,
            'workflow_png':'so.png',
            'user':request.user,
            'current_url':base_url+'/so/',
            'begintime':begintime,
            'endtime':endtime,
            'keywords':keywords,
            }

@register.inclusion_tag('inc_func/stockout/items_list.html', takes_context=True)
def show_so_items_list(context,id):
    result_items = StockOutItem.objects.filter(StockOut__id=id).order_by('id')
    so = StockOut.objects.get(pk=id)
    so.user = context['request'].user
    return {'items':result_items,'id':id,'status':so,'current_url':base_url+'/so/',}

@register.inclusion_tag('inc_func/status.html', takes_context=True)
def show_so_status(context,id):
    request = context['request']
    p = StockOut.objects.get(pk=id)
    p.user = request.user
     
    return {'title':'出库','id':id,'obj':p, 'statuslist':StockOutStatusList,
            'current_url':base_url+'/so/',}

@register.inclusion_tag('inc/task.inc', takes_context=True)
def show_pr_task(context):
    request = context['request']
    items = PurchaseRequest.objects.filter(PR_Ststus__in=['S'])
    items = items.filter(Q(PR_Adult_User__Emp_User = request.user))
    items = items.order_by('-PR_LastModify_Date')     
    return {'title':'采购申请审批','items':items,'current_url':base_url+'/pr/',}

@register.inclusion_tag('inc/task.inc', takes_context=True)
def show_po_task(context):
    request = context['request']
    items = PurchaseOrder.objects.filter(PO_Ststus__in=['S'])
    items = items.filter(Q(PO_Employee_Audit__Emp_User = request.user))
    items = items.order_by('-PO_LastModify_Date')
    return {'title':'采购订单审批','items':items,'current_url':base_url+'/po/',}

@register.inclusion_tag('inc/task.inc', takes_context=True)
def show_re_task(context):
    request = context['request']
    items = PurchaseReceipt.objects.filter(PR_Ststus__in=['S'])
    items = items.filter(Q(PR_ReceiptEmployee__Emp_User = request.user))
    items = items.order_by('-PR_LastModify_Date')     
    return {'title':'入库验收','items':items,'current_url':base_url+'/re/',}

@register.inclusion_tag('inc/task.inc', takes_context=True)
def show_so_task(context):
    request = context['request']
    items = StockOut.objects.filter(Ststus__in=['S'])
    items = items.filter(Q(AuditMan__Emp_User = request.user))
    items = items.order_by('-LastModify_Date')     
    return {'title':'领用出库审批','items':items,'current_url':base_url+'/so/',}


from warehouse.models import PaymentStatusList,Payment_STATUS_CHOICES,Payment

@register.inclusion_tag('inc_func/payment/list.html', takes_context=True)
def show_pa_list(context,pagesize=2,show_pager=0):    
    request = context['request']
    choice = list(Payment_STATUS_CHOICES)
    choice = [x for x,_ in choice]
    begintime = None
    endtime = None
    keywords = None
    page=1
    if request.method == 'POST':
        choice = request.POST.getlist('STATUS_CHOICES')
        begintime = request.POST.get('begintime','')
        endtime = request.POST.get('endtime','')
        keywords = request.POST.get('keywords','')   
    else:
        choice = list( request.GET.get('status',string.join(choice,'')))
        begintime = request.GET.get('begintime','')
        endtime = request.GET.get('endtime','') 
        page = request.GET.get('p','')
        keywords = request.GET.get('keywords','')
        if page:
            page= int(page)
        else:
            page=1
    
    items = Payment.objects.filter(Status__in=choice)
    items = items.filter(Title__contains=keywords)
    
    if begintime:
        items = items .filter( CreateDateTime__gte = datetime.datetime.strptime(begintime,'%Y-%m-%d') )
    if endtime:
        items = items .filter( CreateDateTime__lte = datetime.datetime.strptime(endtime,'%Y-%m-%d') )
    
    #采购列出全部
    #logging.error(in_group(request.user,u'采购'))
    #request.user.groups.all():     
    if request.user.id and in_group(request.user,u'财务') :
        #pr_items = PurchaseRequest.objects.all(PR_Ststus__in=pr_choice).order_by('-PR_LastModify_Date')
        
        #logging.error('ok')
        pass
    else:
        #logging.error( in_group(request.user,u'采购'))        
        username = request.user.id        
        items = items.filter( (~Q(Status='I') & Q(AuditMan__Emp_User__id__exact=username)))
    
    items = items.order_by('-LastModify_Date')
    
    record_count = items.count()
    page_count = str(int(math.ceil(float(record_count)/float(pagesize))))
    first_this_page = (int(page)-1)*pagesize
    last_this_page = min(record_count,int(page)*pagesize)
    
    queryparam = {
                          'query':'?status='+string.join(choice,'')+'&',
                          'qpage':page,                           
                          'record_count':record_count,
                          'pagesize':pagesize,
                          'pagecount':page_count,
                          'first_this_page':first_this_page+1,
                          'last_this_page':last_this_page,
                          #'cache_key':cache_key,
                          #'cache_key_no_page':cache_key_no_page,
                          }  
    items = items[first_this_page :last_this_page]
    return {'items':items,
            'queryparam':queryparam,
            'show_pager':show_pager,
            'STATUS_CHOICES':Payment_STATUS_CHOICES,
            'STATUS_CHOICES_POST':choice,
            'current_url':base_url+'/pa/',
            'workflow_png':'pa.png',
            'begintime':begintime,
            'endtime':endtime,
            'keywords':keywords,
            }

@register.inclusion_tag('inc_func/status.html', takes_context=True)
def show_pa_status(context,id):       
    request = context['request']
    Obj = Payment.objects.get(pk=id)
    Obj.user = request.user    
    return {'id':id,'obj':Obj ,
            'current_url':base_url+'/pa/','statuslist':PaymentStatusList}


@register.inclusion_tag('link.html', takes_context=True)
def jump_link(context):
    return {
        'link': context['home_link'],
        'title': context['home_title'],
    }